package cn.wgx.module.ent.service;

import cn.wgx.common.base.IBaseService;
import cn.wgx.common.entity.ent.EntApp;
import cn.wgx.common.entity.ent.EntUser;
import cn.wgx.common.entity.ent.EntUserApp;
import cn.wgx.common.entity.ent.Enterprise;
import cn.wgx.common.entity.sys.SysApp;
import cn.wgx.common.entity.sys.SysUser;
import cn.wgx.common.security.client.config.entity.LoginAppUser;
import cn.wgx.common.security.util.SysUserUtil;
import cn.wgx.common.util.StringUtils;
import cn.wgx.module.ent.mapper.EnterpriseMapper;
import cn.wgx.module.sys.service.AppService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.List;

@Service
public class EnterpriseService extends IBaseService<EnterpriseMapper, Enterprise> {

    @Autowired
    private EntAppService entAppService;
    @Autowired
    private AppService appService;
    @Autowired
    private EntUserService entUserService;
    @Autowired
    private EntUserAppService entUserAppService;

    private static final String STR_FORMAT = "00000";


    @Transactional(readOnly = true)
    public Integer getCreateUserIdById(Integer ent_id) {
        Enterprise byId = getById(ent_id);
        if(byId != null){
            return byId.getCreateUserId();
        }
        return -1;
    }

    @Transactional(readOnly = true)
    public IPage<Enterprise> page(Page<Enterprise> page) {
        LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser(null);
        if (loginAppUser == null) {
            return page;
        }
        return getBaseMapper().listMyEnt(page, loginAppUser.getUser_id());
    }


    //新增企业包含多个步骤,1.注册企业,2.创建者加入企业,3.企业添加APP 4.创建者添加app
    @Transactional
    public boolean save(Enterprise enterprise) {
        enterprise.setPid(0);
        enterprise.setTop_pid(0);
        boolean b = super.save(enterprise);
        if (b) {
            //初始化企业部门的entcode、code
            iniEntCode(enterprise);
            //如果创建的是企业不是部门
            if (0 == enterprise.getPid()) {
                //2.创建者加入企业
                EntUser entUser = new EntUser();
                entUser.setUser_id(enterprise.getCreateUserId());
                entUser.setEnt_id(enterprise.getEnt_id());
                entUser.setEntCode(enterprise.getEntCode());
                entUserService.save(entUser);

                List<SysApp> list = appService.list();
                if (list.size() != 0) {
                    EntApp entApp = new EntApp();
                    EntUserApp entUserApp = new EntUserApp();
                    for (SysApp sysApp : list) {
                        //3.企业添加app
                        entApp.setEnt_id(enterprise.getEnt_id());
                        entApp.setApp_id(sysApp.getApp_id());
                        entAppService.save(entApp);
                        //4.创建者添加App
                        QueryWrapper<EntUserApp> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("ent_user_id", enterprise.getCreateUserId())
                                .eq("app_id", sysApp.getApp_id())
                                .eq("ent_id", enterprise.getEnt_id());
                        EntUserApp one = entUserAppService.getOne(queryWrapper);
                        if (one == null) {
                            entUserApp.setEnt_user_id(enterprise.getCreateUserId());
                            entUserApp.setEnt_id(enterprise.getEnt_id());
                            entUserApp.setEntCode(enterprise.getEntCode());
                            entUserApp.setApp_id(sysApp.getApp_id());
                            entUserAppService.save(entUserApp);
                        }
                    }
                }

            }
        }

        return b;
    }

    //设置entCode, E父ID + E自己ID + E
    private boolean iniEntCode(Enterprise enterprise) {
        if (enterprise.getEnt_id() == null || enterprise.getEnt_id().equals(0)) {
            return false;
        }
        //初始化entcode
        String pcode = "E";
        //初始化code
        if (enterprise.getPid() == 0) {//创建企业时才需要初始化code
            Integer inicode = 0;
            List<Enterprise> list = list(new QueryWrapper<Enterprise>().eq("pid", 0).orderByDesc("createDate"));
            if (list.size() >= 2 && StringUtils.isNotBlank(list.get(1).getCode())) {
                inicode = Integer.parseInt(list.get(1).getCode().substring(1));
            }
            inicode++;
            String code = new DecimalFormat(STR_FORMAT).format(inicode);
            enterprise.setCode("C" + code);
        }

        enterprise.setEntCode(pcode + enterprise.getEnt_id() + "E");
        Enterprise enterprise1 = new Enterprise();
        enterprise1.setEnt_id(enterprise.getEnt_id());
        enterprise1.setEntCode(enterprise.getEntCode());
        enterprise1.setCode(enterprise.getCode());
        baseMapper.updateById(enterprise1);
        return true;
    }

    //根据entCode查找
    @Transactional(readOnly = true)
    public Enterprise getByCode(String entCode) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("entCode", entCode);
        List<Enterprise> enterprises = list(queryWrapper);
        if (!enterprises.isEmpty()) {
            return enterprises.get(0);
        }
        return null;
    }

    //查找企业名称（判断唯一）
    @Transactional(readOnly = true)
    public Enterprise getEntByName(String name) {
        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper();
        queryWrapper.eq("top_pid", 0).eq("name", name);
        return getOne(queryWrapper);
    }

    @Transactional(readOnly = true)
    public List<SysUser> getUserNotInEnt(Page<SysUser> page, Integer ent_id, String nickname) {
        if (StringUtils.isNotBlank(nickname)) {
            Page<SysUser> page1 = baseMapper.listUserNotInEnt(page, ent_id, "%" + nickname + "%");
            return page1.getRecords();
        } else {
            Page<SysUser> page1 = baseMapper.listUserNotInEnt(page, ent_id, "%" + "" + "%");
            return page1.getRecords();
        }
    }
//    //变树
//    public static JSONArray sortEnt(List<Enterprise> enterprises) {
//        JSONArray jsonArray = new JSONArray();
//        JSONArray jsonArray_tmp = new JSONArray();
//        for (int n = enterprises.size(), i = 0; i < n; i++) {
//            Enterprise enterprise = enterprises.get(i);
//            if (enterprise.getPid() == 0) {
//                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSON(enterprise).toString());
//                jsonArray.add(jsonObject);
//                jsonArray_tmp.add(jsonObject);
//                enterprises.remove(i);
//                i--;
//                n = enterprises.size();
//            }
//        }
//        addEnt(enterprises, jsonArray_tmp);
//        return jsonArray;
//    }
//
//    private static void addEnt(List<Enterprise> enterprises, JSONArray jsonArray_tmp) {
//        int len = enterprises.size();
//        for (int n = len, i = 0; i < n; i++) {
//            Enterprise enterprise = enterprises.get(i);
//            for (Object o : jsonArray_tmp) {
//                JSONObject s = (JSONObject) o;
//                if (enterprise.getPid().equals(s.getLong("ent_id"))) {
//                    JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSON(enterprise).toString());
//                    JSONArray jsonArray1 = s.getJSONArray("children");
//                    if (jsonArray1 == null) {
//                        jsonArray1 = new JSONArray();
//                        s.put("children", jsonArray1);
//                    }
//                    jsonArray1.add(jsonObject);
//                    jsonArray_tmp.add(jsonObject);
//                    enterprises.remove(i);
//                    i--;
//                    n = enterprises.size();
//                    break;
//                }
//            }
//        }
//        int len_end = enterprises.size();
//        if (len_end == 0 || len_end == len) {
//            //结束
//        } else {
//            addEnt(enterprises, jsonArray_tmp);
//        }
//    }
}
